package com.csw.android.androidtest.module.thread;


import android.os.Handler;
import android.os.Looper;
import android.view.View;

import com.csw.android.androidtest.ui.LogViewFragment;
import com.csw.android.androidtest.view.LogView;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.schedulers.Schedulers;


/**
 * Android中限制了更新ui的方法只能在主线程调用，主线程也是Looper线程，可以通过Handler机制切换到主线程执行
 * <p>
 * 最常用的用法有三种：
 * mainHandler.post
 * activity.runOnUiThread
 * view.post
 */
public class ToMainThreadTest extends LogViewFragment {

    @Override
    public void initData() {
        super.initData();
        logView.clearLog();
        //直接通过handler.post，将任务提交到主线程looper消息队列，等待处理
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                logView.addLog("handler.post");
            }
        });
        //activity.runOnUiThread，方法内部实现，判断当前是否处于主线程，是的话直接执行，否则post到消息队列
        Disposable disposable = Observable.empty().observeOn(Schedulers.io()).doOnComplete(new Action() {
            @Override
            public void run() throws Exception {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        logView.addLog("activity.runOnUiThread1");
                    }
                });
            }
        }).subscribe();
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                logView.addLog("activity.runOnUiThread2");
            }
        });
        //view.post 则是在view处于attachwindows时才执行，否则存入缓存队列等到view添加到窗口上再执行
        View view = new View(getContext());
        view.post(new Runnable() {
            @Override
            public void run() {
                logView.addLog("view.post");
            }
        });
        //延迟添加到视图树上
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                logView.addView(view);
            }
        }, 5000);
    }
}
